<template>
  <el-dialog
    v-model="dialogShow"
    title="动态请求配置"
    width="60%"
    @open="open"
    @close="close"
    top="10px"
    :z-index="99"
  >
    <div class="cont">
      <div :class="['global', down ? 'up' : 'down']">
        <div class="title">全局公共配置</div>
        <div class="base-url">
          <div class="name">服务</div>
          <el-input
            placeholder="前置URL 例：127.0.0.1"
            class="url-inp"
            v-model="requestGlobalConfig.requestOriginUrl"
            :disabled="globalDisable"
          ></el-input>
          <el-input
            placeholder="更新间隔时间"
            class="time-inp"
            v-model="requestGlobalConfig.requestInterval"
            :disabled="globalDisable"
          ></el-input>
          <el-select
            class="unit"
            v-model="requestGlobalConfig.requestIntervalUnit"
            :disabled="globalDisable"
          >
            <el-option
              v-for="(val, key) in timeUnit"
              :key="key"
              :label="val"
              :value="key"
            ></el-option>
          </el-select>
          <div class="edit-btn" @click="setEdit">编辑配置</div>
        </div>
        <div class="head-set">
          <div class="title">Header</div>
          <div class="h-table">
            <EditTable
              :target="requestGlobalConfig.requestParams.Header"
              :disabled="globalDisable"
              @update="updateTable"
            />
          </div>
        </div>
        <div class="up-down" @click="upDown">
          {{ down ? "收起" : "下拉" }}
        </div>
      </div>
      <div class="url-router">
        <div class="router">
          <div class="name">地址</div>

          <div class="all-url">
            <el-select
              class="method"
              v-model="selectedComponent.request.requestHttpType"
            >
              <el-option
                v-for="(method, key) of methodArray"
                :key="key"
                :label="method"
                :value="method"
              ></el-option>
            </el-select>
            <span
              class="base-url"
              :title="requestGlobalConfig.requestOriginUrl"
            >
              {{ requestGlobalConfig.requestOriginUrl }}
            </span>
            <el-input
              placeholder="请求地址"
              class="url-inp"
              v-model="selectedComponent.request.requestUrl"
              :readonly="requestContentType == 0"
            ></el-input>
          </div>

          <el-input
            placeholder="更新间隔时间"
            class="time-inp"
            v-model="selectedComponent.request.requestInterval"
          ></el-input>
          <el-select
            class="unit"
            v-model="selectedComponent.request.requestIntervalUnit"
          >
            <el-option
              v-for="(val, key) in timeUnit"
              :key="key"
              :label="val"
              :value="key"
            ></el-option>
          </el-select>
        </div>
        <div class="type">
          <div class="name">请求方式</div>
          <div class="item">
            <div
              v-for="(type, key) in requestContentTypeArray"
              :class="['i-type', requestContentType == key ? 'active' : '']"
              @click="changeRequestType(key)"
            >
              {{ type }}
            </div>
          </div>
        </div>
        <div class="cont">
          <div class="data-source" v-if="requestContentType == 0">
            <div
              class="data-item"
              v-for="(item, key) of datasetData"
              :key="key"
            >
              <div class="key">{{ key }}</div>
              <el-select class="value" v-model="datasetData[key]">
                <el-option
                  v-for="source of sourceArray"
                  :key="source.dataCode"
                  :value="source.dataCode"
                  :label="source.dataName"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="data-source" v-if="requestContentType == 1">
            <commonConfig />
          </div>
        </div>
      </div>
      <div class="footer">
        <el-button @click="close" type="primary">取 消</el-button>
        <el-button @click="save" type="primary">保 存</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import EditTable from "./editTable.vue"
import { getDataSetting } from "../../../../../../../api/dataSource.js"
import { setComponentSource } from "../../../../../../../api/editComponent.js"
import { useStore } from "vuex"
import { ElMessage } from "element-plus"
import {
  timeUnit,
  methodArray,
  requestContentTypeArray,
} from "../../../../../../../packages/public/publicConfig.js"
import commonConfig from "./commonConfig.vue"
let store = useStore()

let props = defineProps({
  ajaxShow: {
    type: Boolean,
    default: false,
  },
})
let emit = defineEmits(["update:ajaxShow"])

let down = ref(false)

let sourceArray = ref([])
let globalDisable = ref(true)
let dialogShow = computed(() => {
  return props.ajaxShow
})
let requestGlobalConfig = computed(() => {
  return store.state.chartEditStore.requestGlobalConfig
})
let selectedComponent = computed(() => {
  return store.state.chartEditStore.selectedComponent
})
let requestContentType = computed(() => {
  return selectedComponent.value.request.requestContentType
})
let datasetData = computed(() => {
  let data = selectedComponent.value.option.dataset?.config ?? {}
  if (!typeof data == "object" && data != null && Array.isArray(data)) {
    ElMessage.error("数据源key值需为对象")
    return {}
  }
  return data
})
function open() {
  getData()
}

watch(
  requestContentType,
  val => {
    if (val == 0) {
      selectedComponent.value.request.requestUrl = `${selectedComponent.value.request.requestDatasourceUrl}/${selectedComponent.value.id}`
    }
  },
  { immediate: true }
)

function close() {
  emit("update:ajaxShow", false)
  globalDisable.value = true
}

async function save() {
  if (requestContentType.value == 0) {
    let source = datasetData.value
    let dataMap = []
    if (JSON.stringify(source) == "{}") {
      ElMessage.error("该组件没有数据源")
      return
    }
    for (let key in source) {
      if (source[key] == "" || source[key] == null) {
        dataMap = []
        ElMessage.warning("数据源数值不能为空")
        return
      }
      dataMap.push({
        dataCode: source[key],
        modelKey: key,
      })
    }
    try {
      let res = await setComponentSource({
        componentCode: selectedComponent.value.id,
        componentType: selectedComponent.value.chartConfig.key,
        dataCodeAndModelKeyMappers: dataMap,
      })
      if (res.status) {
        ElMessage.success("保存成功")
        close()
      } else {
        ElMessage.error(res?.data?.message || "保存失败")
      }
    } catch (e) {
      ElMessage.error(
        e.response?.data?.data?.message || e.message || "保存失败"
      )
    }
  } else {
    close()
  }
}

function upDown() {
  down.value = !down.value
}

async function getData() {
  sourceArray.value = []
  let res = await getDataSetting()
  if (res.status) {
    sourceArray.value = res.data
  }
}

function changeRequestType(type) {
  selectedComponent.value.request.requestContentType = type
}

function setEdit() {
  globalDisable.value = false
}

function updateTable(value) {
  requestGlobalConfig.value.requestParams.Header = value
}
</script>
<style scoped lang="scss">
.cont {
  max-height: 600px;
  overflow: auto;
  .global {
    position: relative;
    padding-bottom: 40px;
    overflow: hidden;
    transition: all 0.5s;
    .title {
      height: 30px;
      line-height: 30px;
      font-size: 16px;
    }
    .base-url {
      display: flex;
      height: 60px;
      align-items: center;
      .name {
        width: 80px;
        line-height: 30px;
        text-align: right;
        padding: 0 5px;
      }
      .url-inp {
        width: 40%;
        margin: 0 20px;
      }
      .time-inp {
        width: 120px;
      }
      .unit {
        width: 80px;
      }
      .edit-btn {
        margin-left: 20px;
        width: 100px;
        cursor: pointer;
        line-height: 30px;
        text-align: center;
        border: 1px solid #51d6a9;
        color: #51d6a9;
        border-radius: 4px;
      }
    }
    .head-set {
      .title {
        height: 30px;
        line-height: 30px;
        font-size: 16px;
      }
    }
    .up-down {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 30px;
      line-height: 30px;
      text-align: center;
      cursor: pointer;
      background-color: #d9d9d9;
      border-radius: 4px;
    }
  }
  .down {
    transition: all 1s;
    height: 120px;
  }
  .url-router {
    margin-top: 20px;
    border-top: 1px solid #999;
    padding: 10px 0;
    .router {
      display: flex;
      height: 60px;
      align-items: center;
      .name {
        width: 80px;
        line-height: 30px;
        text-align: right;
        padding: 0 5px;
      }

      .all-url {
        display: flex;
        align-items: center;
        margin: 0 20px;
        border: 1px solid #999;
        border-radius: 4px;
        .method {
          width: 180px;
        }
        .base-url {
          display: inline-block;
          height: 30px;
          line-height: 30px;
          min-width: 160px;
          max-width: 200px;
          padding: 0 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .url-inp {
          min-width: 200px;
          max-width: 300px;
        }
      }
      .time-inp {
        width: 100px;
      }
      .unit {
        width: 80px;
      }
    }
    .type {
      display: flex;
      height: 40px;
      align-items: center;
      .name {
        width: 80px;
        line-height: 30px;
        text-align: right;
        padding: 0 5px;
      }
      .item {
        margin-left: 20px;
        width: 300px;
        display: flex;
        border: 1px solid #999;
        padding: 1px;
        border-radius: 4px;
        .i-type {
          width: 150px;
          height: 30px;
          line-height: 30px;
          cursor: pointer;
          text-align: center;
          border-radius: 4px;
        }
        .active {
          color: #0084fe;
          background-color: #d3eafe;
        }
      }
    }
  }
  .cont {
    margin-top: 10px;
    .data-source {
      padding: 10px;
      .data-item {
        display: flex;
        align-items: center;
        height: 40px;
        .key {
          width: 80px;
          text-align: right;
          line-height: 40px;
          margin-right: 10px;
          padding: 0 5px;
        }
        .value {
          width: 200px;
        }
      }
    }
  }
  .footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
